import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";
class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;
  direction: string;
  isLive: boolean;
  constructor() {
    this.snake = new Snake();
    this.food = new Food();
    this.scorePanel = new ScorePanel();
    this.direction = '';
    /* 蛇是否还活着,标志游戏是否结束 */
    this.isLive = true;
    this.init();
  }
  init() {
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.move();
  }
  keydownHandler(e: KeyboardEvent) {
    this.direction = e.key;
  }
  CheckEatFood(x:number, y:number) {
    if (x === this.food.X && y === this.food.Y) {
      this.food.changePos();
      this.scorePanel.addScore();
      this.snake.addBody();
    }
  }
  move() {
    let X = this.snake.HeadX;
    let Y = this.snake.HeadY;
    switch (this.direction) {     
      case 'ArrowUp':
        Y = Y - 10;
        break;
      case 'ArrowRight':
        X = X + 10;
        break;
      case 'ArrowLeft':
        X = X - 10;
        break;
      case 'ArrowDown':
        Y = Y + 10;
        break;
    }
    try {
      this.snake.HeadX = X;
      this.snake.HeadY = Y;
      this.CheckEatFood(X,Y);
      this.snake.moveBody();
    } catch (error) {
      alert('蛇撞墙了 游戏结束!');
      this.isLive = false;
    }
    if (this.isLive) {
      setTimeout(() => {
        this.move();
      }, 130 - (this.scorePanel.level * 30));
    }
  }
}

export default GameControl